﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Configuration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Drawing;
using System.Web.Profile;
using System.Collections.Generic;

/*
Developed By: Sujeet Kumar
Modified By: Sujeet
Modified on: 16th September 2010
Description: The code provides the Project site  to display display all users.   
*/
namespace SiteProjects.Project_Users
{
    public partial class Project_UsersUserControl : UserControl
    {
        string urlCurrent = string.Empty;
        string projectUrl = string.Empty;
        string[] arryUrlCurrent;
        DataTable dtUsers,dtUniqueUser;
        protected void Page_Load(object sender, EventArgs e)
        {
            GetProjectUsers();

        }

        /// <summary>
        ///  Get and Bind a data in grid
        /// </summary>
        //public void GetProjectUrl()
        //{
        //    try
        //    {
        //        SqlConnection connection = new SqlConnection();
        //        SqlCommand command;
        //        DataSet ds;
        //        SqlDataAdapter adapter;

        //        SPSite webSite = SPContext.Current.Site; //get the current site
        //        urlCurrent = webSite.Url; //get the web site url

        //        arryUrlCurrent = urlCurrent.Split(new char[] { '/' }); // Split the Url On Base of "/" //

        //        lblMessage.Visible = false;
        //        StringBuilder url = new StringBuilder();
        //        projectUrl = string.Empty;

        //        int count;
        //        for (count = 3; count < arryUrlCurrent.Length; count++)
        //        {
        //            url.Append("/" + arryUrlCurrent[count].ToString());   //get the URL //
        //        }
        //        projectUrl = url.ToString().Substring(1, url.Length - 1);

        //        //connection fetch by web.config file and stored procedure call
        //        connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ASPNET_WSS_Content"].ConnectionString);
        //        command = new SqlCommand("proc_Show_user_project", connection);  // Calling Stored procedure //
        //        command.Parameters.AddWithValue("@projecturl", projectUrl.ToString()); //passing Parameter to StoredProcedure //
        //        command.CommandType = CommandType.StoredProcedure;
        //        ds = new DataSet();
        //        adapter = new SqlDataAdapter(command);
        //        //connection open
        //        connection.Open();
        //        adapter.Fill(ds);
        //        //connection close
        //        connection.Close();
        //        if (ds.Tables[0].Rows.Count == 0)
        //        {
        //            lblMessage.Text = "There are no items to show in this view.";
        //            lblMessage.Visible = true;
        //        }
        //        else
        //        {
        //            //bind the data in grid
        //            gvShowProjectUsers.DataSource = ds;
        //            gvShowProjectUsers.DataBind();
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        lblMessage.Visible = true;
        //        lblMessage.Text = ex.Message;
        //        lblMessage.ForeColor = Color.Red;
        //    }
        //}

        /// <summary>
        /// Paging
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvShowProjectUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvShowProjectUsers.PageIndex = e.NewPageIndex;
            gvShowProjectUsers.DataBind();
        }

        /// <summary>
        /// Bind the each row to the grid view.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvShowProjectUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            HyperLink hlkProjectUser;
            Label lblProjectUser;
            Label lblProfileAccountName;
            string userName = string.Empty;
            string accountName = string.Empty;
            string profileUrl = string.Empty;
            //website used to get the title,url and display in label and hyperlink
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string temp = string.Empty;
                lblProjectUser = (System.Web.UI.WebControls.Label)(e.Row.Cells[0].FindControl("lblProjectUser"));
                lblProfileAccountName = (System.Web.UI.WebControls.Label)(e.Row.Cells[0].FindControl("lblProfileAccountName"));
                hlkProjectUser = (System.Web.UI.WebControls.HyperLink)(e.Row.Cells[1].FindControl("hlkProjectUser"));
                hlkProjectUser.Text = lblProjectUser.Text;
                userName = lblProjectUser.Text.ToString();
                accountName = lblProfileAccountName.Text.ToString();
                if (accountName.Contains("i:0#.f|sqlmember|"))
                {
                    temp = "%3A0%23";
                    accountName = accountName.Replace(":0#", temp);
                    temp = "%40";
                    accountName = accountName.Replace("@", temp);
                }
                else if (accountName.Contains("i:0#.w"))
                {
                    temp = "i%3A0%23.w";
                    accountName = accountName.Replace("i:0#.w", temp);
                }
                profileUrl = "http://" + arryUrlCurrent[2] + "/person.aspx?accountname=" + accountName;
                hlkProjectUser.NavigateUrl = profileUrl;
            }
        }

        /// <summary>
        ///  Get and Bind a data in grid 
        /// </summary>
        public void GetProjectUsers()
        {
            dtUsers = new DataTable();
            dtUniqueUser = new DataTable();
            dtUniqueUser.Columns.Add("User Name", typeof(string));
            dtUniqueUser.Columns.Add("User LoginName", typeof(string));
            dtUsers.Columns.Add("User Name", typeof(string));
            dtUsers.Columns.Add("User LoginName", typeof(string));
            try
            {
                SPSite webSite = SPContext.Current.Site; //get the current site
                urlCurrent = webSite.Url; //get the web site url
                string urlCurrent1 = webSite.Url;
                arryUrlCurrent = urlCurrent.Split(new char[] { '/' }); // Split the Url On Base of "/" //

                lblMessage.Visible = false;
                StringBuilder url = new StringBuilder();
                projectUrl = string.Empty;

                int count;
                for (count = 3; count < arryUrlCurrent.Length; count++)
                {
                    url.Append("/" + arryUrlCurrent[count].ToString());   //get the URL //
                }
                projectUrl = url.ToString().Substring(1, url.Length - 1);

                //  using (SPWeb oWeb = SPContext.Current.Site.OpenWeb())
                // {
                SPWeb oWeb = SPContext.Current.Web;
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite Elevatedsite = new SPSite(oWeb.Site.Url))
                    {
                        using (SPWeb ElevatedWeb = Elevatedsite.OpenWeb())
                        //using (SPWeb ElevatedWeb = SPContext.Current.Site.OpenWeb())
                        {
                            foreach (SPGroup userGroup in ElevatedWeb.Groups)
                            {
                                SPUserCollection userColl = userGroup.Users;

                                foreach (SPUser user in userColl)
                                {
                                    DataRow row = dtUsers.NewRow();
                                    row["User Name"] = user.Name;
                                    row["User LoginName"] = user.LoginName;
                                    dtUsers.Rows.Add(row);
                                }
                            }
                        }
                    }
                });
                // dtUsers= dtUsers.DefaultView.ToTable( true,"User Name" );
                IEnumerable<DataRow> uniqueUsers = dtUsers.AsEnumerable().Distinct(DataRowComparer.Default);
                foreach (DataRow uniqueRow in uniqueUsers)
                {
                    DataRow row = dtUniqueUser.NewRow();
                    row["User Name"] = uniqueRow["User Name"];
                    row["User LoginName"] = uniqueRow["User LoginName"];
                    dtUniqueUser.Rows.Add(row);

                }

                if (dtUniqueUser.Rows.Count == 0)
                {
                    lblMessage.Text = "There are no items to show in this view.";
                    lblMessage.Visible = true;
                }
                else
                {
                    //bind the data in grid
                    gvShowProjectUsers.DataSource = dtUniqueUser;
                    gvShowProjectUsers.DataBind();

                }

            }
            catch (Exception ex)
            {
                lblMessage.Visible = true;
                lblMessage.Text = ex.Message;
                lblMessage.ForeColor = Color.Red;
            }

        }

        protected void hlkAddLink_Click(object sender, EventArgs e)
        {
            SPSite webSite = SPContext.Current.Site; //get the current site
                urlCurrent = webSite.Url; 
            Response.Redirect(urlCurrent + "/_layouts/aclinv.aspx");
        }

    

    }
}
